package com.wuming.caiwu.controller;

import com.wuming.caiwu.core.BusinessException;
import com.wuming.caiwu.core.CommonResult;
import com.wuming.caiwu.core.JsonResult;
import com.wuming.caiwu.model.Member;
import com.wuming.caiwu.security.SecurityHander;
import com.wuming.caiwu.service.MemberService;
import com.wuming.caiwu.util.EncodeUitl;
import com.wuming.caiwu.util.SHAUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by hanfei on 16/4/19.
 */
@Controller
@RequestMapping("/web/member")
public class MemberController extends BaseController {

    @Autowired
    private MemberService memberService;


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(RedirectAttributesModelMap redirectModelMap, Member member) {
        try {
            String password = member.getPassword();
            password = SHAUtil.shaEncode(password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(member.getUserName(), password));
            if (!subject.isAuthenticated()) {
                redirectModelMap.addAttribute("result", "error");
                redirectModelMap.addAttribute("msg", EncodeUitl.encode("用户名或密码错误!"));
                return "redirect:/result.jsp";
            }
            member = memberService.getMemberByNameAndPassword(member.getUserName(), password);
//            redirectModelMap.addAttribute("userId", String.valueOf(member.getId()));
//            List<SysPermission> permissions = sysPermissionService.getPermissionByUserId(member.getId().longValue());
            return "redirect:/web/index.htmls";
//            model.addAttribute("permissions",permissions);
//            return "/main/index";
        } catch (AuthenticationException e) {
            redirectModelMap.addAttribute("msg", EncodeUitl.encode("用户名或密码错误!"));
            return "redirect:/result.jsp";
        } catch (Exception e) {
            redirectModelMap.addAttribute("msg", EncodeUitl.encode("业务错误!"));
            return "redirect:/result.jsp";
        }
    }

    @ResponseBody
    @RequestMapping(value = "getChildrens",method = RequestMethod.GET)
    public JsonResult getChildrens(Integer memberId){
        return new JsonResult(memberService.getChildrens(memberId),"",true);
    }


    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpSession httpSession) {
        // 登出操作
        Subject subject = SecurityUtils.getSubject();
        Integer id = SecurityHander.getCurrentUserId();
        String userName = SecurityHander.getCurrentUserName();
        subject.logout();
        return "redirect:/login_new.jsp";
    }


    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public JsonResult saveMember(Member member) {
        try {
            Member member1 = memberService.getMemberByPhone(member.getPhone());
            if (null == member1) {
                String password = member.getPassword();
                password = SHAUtil.shaEncode(password);
                member.setPassword(password);
                member.setCreateTime(new Date());
                member.setBlance(new BigDecimal(0));
                memberService.saveMember(member);
                return new JsonResult<Object>(null, "注册用户成功", true);
            }
            return new JsonResult<Object>(null, "手机号已经注册,请更换手机号.", false);
        } catch (BusinessException be) {
            logger.error("发生业务异常,异常信息:{}", be.getMessage());
        } catch (Exception e) {
            logger.error("发生系统异常,异常信息:{}", e.getMessage());
        }
        return new JsonResult<Object>(null, "注册失败,请联系系统管理员.", false);
    }

    @RequestMapping(value = "toAddMember", method = RequestMethod.GET)
    public String toAddMember() {
        return "/user/addMember";
    }

    @RequestMapping(value = "manageMember", method = RequestMethod.GET)
    public String manageMember() {
        return "/user/manageMember";
    }

    @RequestMapping(value = "manageChildMembers", method = RequestMethod.GET)
    public String manageChildMembers() {
        return "/user/manageChildMember";
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public CommonResult list(@RequestParam(defaultValue = "0") int pageIndex, @RequestParam(defaultValue = "10") int pageSize, @RequestParam(required = false) Integer memberId, @RequestParam(required = false) String userName, @RequestParam(required = false) String company, @RequestParam(required = false) String phone, @RequestParam(required = false) Integer status) {
        try {
            Member current = memberService.getMemberById(memberId);
            if(memberService.isAdministrator(current)){
                List<Member> members = memberService.getMembersByPage(pageIndex, pageSize, null, userName, company, phone, status, null);
                int total = memberService.getTotal(null, userName, company, phone, status, null);
                return CommonResult.createSuccessResult(members, total, "查询用户数量成功");
            }else{
                List<Member> members = memberService.getMembersByPage(pageIndex, pageSize, null, userName, company, phone, status, memberId);
                int total = memberService.getTotal(null, userName, company, phone, status, memberId);
                return CommonResult.createSuccessResult(members, total, "查询用户数量成功");
            }
        } catch (BusinessException be) {
            logger.error("发生业务异常,异常信息:{}", be.getMessage());
            return CommonResult.createSuccessResult("查询学员信息失败");
        } catch (Exception e) {
            logger.error("发生系统异常,异常信息:{}", e.getMessage());
            return CommonResult.createSuccessResult("查询学员信息失败");
        }
    }


    @ResponseBody
    @RequestMapping(value = "/listChildMembers", method = RequestMethod.POST)
    public CommonResult listChildMembers(@RequestParam(required = false) Integer parentId, @RequestParam(required = false) String userName, @RequestParam(required = false) String company, @RequestParam(required = false) String phone, @RequestParam(required = false) Integer status, @RequestParam(defaultValue = "0") int pageIndex, @RequestParam(defaultValue = "10") int pageSize) {
        try {
            List<Member> members = memberService.getMembersByPage(pageIndex, pageSize, null, userName, company, phone, status, parentId);
            int total = memberService.getTotal(null, userName, company, phone, status, parentId);
            return CommonResult.createSuccessResult(members, total, "查询下级会员成功");
        } catch (BusinessException be) {
            logger.error("发生业务异常,异常信息:{}", be.getMessage());
            return CommonResult.createSuccessResult("查询下级会员失败");
        } catch (Exception e) {
            logger.error("发生系统异常,异常信息:{}", e.getMessage());
            return CommonResult.createSuccessResult("查询下级会员失败");
        }
    }

    @RequestMapping(value = "/editMember/{id}", method = RequestMethod.GET)
    public String editUser(@PathVariable Integer id, Model model) {
        logger.info("准备修改学员信息ID:{}", id);
        Member member = memberService.getMemberById(id);
        model.addAttribute("member", member);
        return "/user/editMember";
    }

    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public CommonResult editMember(Member member) {
        try {
            memberService.modifyMember(member);
            Member current = memberService.getMemberById(member.getId());
            return CommonResult.createSuccessResult("保存注册用户成功.");
        } catch (BusinessException be) {
            logger.error("发生业务异常,异常信息:{}", be.getMessage());
            return CommonResult.createFailureResult("保存注册用户失败.");
        } catch (Exception e) {
            logger.error("发生系统异常,异常信息:{}", e.getMessage());
            return CommonResult.createFailureResult("保存注册用户失败.");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public CommonResult deteleMember(@PathVariable Integer id) {
        logger.info("准备注册用户信息ID:{}", id);
        try {
            memberService.removeMemberById(id);
            return CommonResult.createSuccessResult("删除注册用户成功");
        } catch (BusinessException be) {
            logger.error("发生业务异常,异常信息:{}", be.getMessage());
            return CommonResult.createFailureResult("删除注册用户失败.");
        } catch (Exception e) {
            logger.error("发生系统异常,异常信息:{}", e.getMessage());
            return CommonResult.createFailureResult("删除注册用户失败.");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/resetPass/{id}", method = RequestMethod.GET)
    public CommonResult resetPass(@PathVariable Integer id) {
        logger.info("准备重置用户密码ID:{}", id);
        try {
            Member current = memberService.getMemberById(id);
            current.setPassword(SHAUtil.shaEncode("123"));
            memberService.modifyMember(current);
            return CommonResult.createSuccessResult("准备重置用户密码成功");
        } catch (BusinessException be) {
            logger.error("发生业务异常,异常信息:{}", be.getMessage());
            return CommonResult.createFailureResult("准备重置用户密码失败.");
        } catch (Exception e) {
            logger.error("发生系统异常,异常信息:{}", e.getMessage());
            return CommonResult.createFailureResult("准备重置用户密码失败.");
        }
    }


    @RequestMapping(value = "/toModifyPassword/{id}", method = RequestMethod.GET)
    public String toModifyPassword(@PathVariable Integer id, Model model) {
        logger.info("准备修改会员{}的密码", id);
        Member member = memberService.getMemberById(id);
        model.addAttribute("member", member);
        return "/user/modifyPassword";
    }

    @ResponseBody
    @RequestMapping(value = "/modifyPass", method = RequestMethod.POST)
    public JsonResult modifyPass(Integer memberId, String oldPassword, String password, HttpServletRequest request) {
        logger.info("修改会员{}的密码", memberId);
        try {
            Member member = memberService.getMemberById(memberId);
            password = SHAUtil.shaEncode(password);
            if (!SHAUtil.shaEncode(oldPassword).equals(member.getPassword())) {
                return new JsonResult(null, "旧密码验证错误", false);
            }
            if (password.equals(member.getPassword())) {
                return new JsonResult(null, "与旧密码重复", false);
            }
            member.setPassword(password);
            memberService.modifyMember(member);
        } catch (BusinessException be) {
            logger.error("发生业务异常,异常信息:{}", be.getMessage());
            return new JsonResult(null, "修改会员的密码失败.", false);
        } catch (Exception e) {
            logger.error("发生系统异常,异常信息:{}", e.getMessage());
            return new JsonResult(null, "修改会员的密码失败.", false);
        }
        return new JsonResult(null, "修改会员的密码成功.", true);
    }

    @RequestMapping(value = "manageOperator", method = RequestMethod.GET)
    public String manageOperator() {
        return "/user/manageOperator";
    }

    @RequestMapping(value = "toEditOperator", method = RequestMethod.GET)
    public String toEditOperator(Model model) {
        model.addAttribute("from","operator");
        return "/user/addMember";
    }
}
